/**
 * 用户状态管理 Store
 * 管理用户认证状态、个人信息和认证操作
 */

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as userApi from '../services/userApi.js';

// Token持久化的localStorage键名
const TOKEN_KEY = 'ai_essay_token';
const USER_INFO_KEY = 'ai_essay_user';

export const useUserStore = defineStore('user', () => {
  // ==================== 状态 ====================

  /**
   * 认证token
   * 从localStorage初始化，确保刷新页面后仍然登录
   */
  const token = ref(localStorage.getItem(TOKEN_KEY) || null);

  /**
   * 用户信息
   * 包含id, username, gradeLevel等
   */
  const userInfo = ref(null);

  /**
   * 加载状态
   */
  const loading = ref(false);

  /**
   * 错误信息
   */
  const error = ref(null);

  // ==================== 计算属性 ====================

  /**
   * 是否已认证
   * 根据token是否存在判断
   */
  const isAuthenticated = computed(() => !!token.value);

  /**
   * 用户ID
   */
  const userId = computed(() => userInfo.value?.id || null);

  /**
   * 用户名
   */
  const username = computed(() => userInfo.value?.username || '');

  /**
   * 学段
   */
  const gradeLevel = computed(() => userInfo.value?.gradeLevel || '');

  // ==================== 操作 ====================

  /**
   * 用户登录
   * @param {Object} credentials - 登录凭证
   * @param {string} credentials.username - 用户名
   * @param {string} credentials.password - 密码
   * @returns {Promise<Object>} 登录结果
   */
  const login = async (credentials) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[UserStore] Login:', credentials.username);

      // 调用真实API
      const response = await userApi.login(credentials);
      const { token: authToken, user } = response.data;

      // 保存token到state和localStorage
      token.value = authToken;
      localStorage.setItem(TOKEN_KEY, authToken);

      // 保存用户信息
      userInfo.value = user;
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(user));

      console.log('[UserStore] Login successful:', user.username);
      return { success: true, data: user };
    } catch (err) {
      const errorMessage = err.message || '登录失败';
      error.value = errorMessage;
      console.error('[UserStore] Login failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 用户注册
   * @param {Object} registerData - 注册数据
   * @param {string} registerData.username - 用户名
   * @param {string} registerData.password - 密码
   * @param {string} registerData.gradeLevel - 学段
   * @returns {Promise<Object>} 注册结果
   */
  const register = async (registerData) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[UserStore] Register:', registerData.username);

      // 调用真实API
      const response = await userApi.register(registerData);
      const { token: authToken, user } = response.data;

      // 保存token到state和localStorage
      token.value = authToken;
      localStorage.setItem(TOKEN_KEY, authToken);

      // 保存用户信息
      userInfo.value = user;
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(user));

      console.log('[UserStore] Register successful:', user.username);
      return { success: true, data: user };
    } catch (err) {
      const errorMessage = err.message || '注册失败';
      error.value = errorMessage;
      console.error('[UserStore] Register failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 用户登出
   * 清除所有认证状态和本地存储
   */
  const logout = () => {
    // 清除state
    token.value = null;
    userInfo.value = null;
    error.value = null;

    // 清除localStorage
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(USER_INFO_KEY);

    console.log('[UserStore] Logged out');
  };

  /**
   * 获取用户资料
   * @returns {Promise<Object>} 用户信息
   */
  const getProfile = async () => {
    if (!token.value) {
      throw new Error('未登录');
    }

    loading.value = true;
    error.value = null;

    try {
      console.log('[UserStore] Get profile');

      // 调用真实API
      const response = await userApi.getProfile();
      const user = response.data.user;

      // 更新用户信息
      userInfo.value = user;
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(user));

      console.log('[UserStore] Profile retrieved successfully');
      return { success: true, data: user };
    } catch (err) {
      const errorMessage = err.message || '获取用户信息失败';
      error.value = errorMessage;
      console.error('[UserStore] Get profile failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新用户资料
   * @param {Object} updates - 要更新的字段
   * @returns {Promise<Object>} 更新后的用户信息
   */
  const updateProfile = async (updates) => {
    if (!token.value) {
      throw new Error('未登录');
    }

    loading.value = true;
    error.value = null;

    try {
      console.log('[UserStore] Update profile:', Object.keys(updates));

      // 调用真实API
      const response = await userApi.updateProfile(updates);
      const updatedUser = response.data.user;

      // 更新用户信息
      userInfo.value = updatedUser;
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(updatedUser));

      console.log('[UserStore] Profile updated successfully');
      return { success: true, data: updatedUser };
    } catch (err) {
      const errorMessage = err.message || '更新用户信息失败';
      error.value = errorMessage;
      console.error('[UserStore] Update profile failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 初始化用户状态
   * 从localStorage恢复用户信息
   */
  const initializeUserState = () => {
    const savedToken = localStorage.getItem(TOKEN_KEY);
    const savedUser = localStorage.getItem(USER_INFO_KEY);

    if (savedToken && savedUser) {
      token.value = savedToken;
      try {
        userInfo.value = JSON.parse(savedUser);
        console.log('[UserStore] Restored user state from localStorage');
      } catch (err) {
        console.error('[UserStore] Failed to parse user info:', err);
        logout();
      }
    }
  };

  // 初始化时尝试恢复状态
  initializeUserState();

  // ==================== 返回 ====================

  return {
    // 状态
    token,
    userInfo,
    loading,
    error,

    // 计算属性
    isAuthenticated,
    userId,
    username,
    gradeLevel,

    // 操作
    login,
    register,
    logout,
    getProfile,
    updateProfile,
    initializeUserState,
  };
});

